import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { 
  getDepartmentTree, 
  getRegistrationList, 
  getMedicalRecordList,
  getMedicineList,
  getWardList
} from '@/api/business'

export const useMedicalStore = defineStore('medical', () => {
  // 状态
  const departments = ref([])
  const registrations = ref([])
  const medicalRecords = ref([])
  const medicines = ref([])
  const wards = ref([])
  
  // 缓存时间戳
  const lastFetchTime = ref({
    departments: 0,
    registrations: 0,
    medicalRecords: 0,
    medicines: 0,
    wards: 0
  })
  
  // 缓存有效期（5分钟）
  const CACHE_DURATION = 5 * 60 * 1000
  
  // 计算属性
  const departmentOptions = computed(() => 
    departments.value.map(dept => ({
      label: dept.name,
      value: dept.id
    }))
  )
  
  const activeWards = computed(() => 
    wards.value.filter(ward => ward.status === 1)
  )
  
  const availableWards = computed(() => 
    activeWards.value.filter(ward => ward.currentPatients < ward.capacity)
  )
  
  const lowStockMedicines = computed(() => 
    medicines.value.filter(medicine => medicine.stock <= medicine.minStock)
  )
  
  const nearExpiryMedicines = computed(() => {
    const thirtyDaysFromNow = new Date()
    thirtyDaysFromNow.setDate(thirtyDaysFromNow.getDate() + 30)
    
    return medicines.value.filter(medicine => {
      const expiryDate = new Date(medicine.expiryDate)
      return expiryDate <= thirtyDaysFromNow && expiryDate > new Date()
    })
  })
  
  // 检查缓存是否有效
  const isCacheValid = (type) => {
    return Date.now() - lastFetchTime.value[type] < CACHE_DURATION
  }
  
  // 获取科室列表
  const fetchDepartments = async (force = false) => {
    if (!force && departments.value.length > 0 && isCacheValid('departments')) {
      return departments.value
    }
    
    try {
      const response = await getDepartmentTree()
      if (response.code === 200) {
        departments.value = response.data
        lastFetchTime.value.departments = Date.now()
        return response.data
      }
    } catch (error) {
      console.error('获取科室列表失败:', error)
      throw error
    }
  }
  
  // 获取挂号列表
  const fetchRegistrations = async (params = {}, force = false) => {
    if (!force && registrations.value.length > 0 && isCacheValid('registrations')) {
      return registrations.value
    }
    
    try {
      const response = await getRegistrationList(params)
      if (response.code === 200) {
        registrations.value = response.data.list || response.data
        lastFetchTime.value.registrations = Date.now()
        return response.data
      }
    } catch (error) {
      console.error('获取挂号列表失败:', error)
      throw error
    }
  }
  
  // 获取就诊记录列表
  const fetchMedicalRecords = async (params = {}, force = false) => {
    if (!force && medicalRecords.value.length > 0 && isCacheValid('medicalRecords')) {
      return medicalRecords.value
    }
    
    try {
      const response = await getMedicalRecordList(params)
      if (response.code === 200) {
        medicalRecords.value = response.data.list || response.data
        lastFetchTime.value.medicalRecords = Date.now()
        return response.data
      }
    } catch (error) {
      console.error('获取就诊记录失败:', error)
      throw error
    }
  }
  
  // 获取药品列表
  const fetchMedicines = async (params = {}, force = false) => {
    if (!force && medicines.value.length > 0 && isCacheValid('medicines')) {
      return medicines.value
    }
    
    try {
      const response = await getMedicineList(params)
      if (response.code === 200) {
        medicines.value = response.data.list || response.data
        lastFetchTime.value.medicines = Date.now()
        return response.data
      }
    } catch (error) {
      console.error('获取药品列表失败:', error)
      throw error
    }
  }
  
  // 获取病房列表
  const fetchWards = async (params = {}, force = false) => {
    if (!force && wards.value.length > 0 && isCacheValid('wards')) {
      return wards.value
    }
    
    try {
      const response = await getWardList(params)
      if (response.code === 200) {
        wards.value = response.data.list || response.data
        lastFetchTime.value.wards = Date.now()
        return response.data
      }
    } catch (error) {
      console.error('获取病房列表失败:', error)
      throw error
    }
  }
  
  // 根据ID获取科室信息
  const getDepartmentById = (id) => {
    return departments.value.find(dept => dept.id === id)
  }
  
  // 根据ID获取药品信息
  const getMedicineById = (id) => {
    return medicines.value.find(medicine => medicine.id === id)
  }
  
  // 根据ID获取病房信息
  const getWardById = (id) => {
    return wards.value.find(ward => ward.id === id)
  }
  
  // 更新单个科室信息
  const updateDepartment = (id, data) => {
    const index = departments.value.findIndex(dept => dept.id === id)
    if (index > -1) {
      departments.value[index] = { ...departments.value[index], ...data }
    }
  }
  
  // 更新单个药品信息
  const updateMedicine = (id, data) => {
    const index = medicines.value.findIndex(medicine => medicine.id === id)
    if (index > -1) {
      medicines.value[index] = { ...medicines.value[index], ...data }
    }
  }
  
  // 更新单个病房信息
  const updateWard = (id, data) => {
    const index = wards.value.findIndex(ward => ward.id === id)
    if (index > -1) {
      wards.value[index] = { ...wards.value[index], ...data }
    }
  }
  
  // 清除所有缓存
  const clearCache = () => {
    departments.value = []
    registrations.value = []
    medicalRecords.value = []
    medicines.value = []
    wards.value = []
    lastFetchTime.value = {
      departments: 0,
      registrations: 0,
      medicalRecords: 0,
      medicines: 0,
      wards: 0
    }
  }
  
  // 清除特定类型的缓存
  const clearCacheByType = (type) => {
    if (type === 'departments') {
      departments.value = []
      lastFetchTime.value.departments = 0
    } else if (type === 'registrations') {
      registrations.value = []
      lastFetchTime.value.registrations = 0
    } else if (type === 'medicalRecords') {
      medicalRecords.value = []
      lastFetchTime.value.medicalRecords = 0
    } else if (type === 'medicines') {
      medicines.value = []
      lastFetchTime.value.medicines = 0
    } else if (type === 'wards') {
      wards.value = []
      lastFetchTime.value.wards = 0
    }
  }
  
  return {
    // 状态
    departments,
    registrations,
    medicalRecords,
    medicines,
    wards,
    
    // 计算属性
    departmentOptions,
    activeWards,
    availableWards,
    lowStockMedicines,
    nearExpiryMedicines,
    
    // 操作
    fetchDepartments,
    fetchRegistrations,
    fetchMedicalRecords,
    fetchMedicines,
    fetchWards,
    getDepartmentById,
    getMedicineById,
    getWardById,
    updateDepartment,
    updateMedicine,
    updateWard,
    clearCache,
    clearCacheByType
  }
}) 